package com.zemb.flxwear.UI.Fragment;

import static java.lang.Thread.sleep;

import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.zemb.flxwear.Bean.ReportItem;
import com.zemb.flxwear.DB.DataBaseHelper;
import com.zemb.flxwear.R;
import com.zemb.flxwear.Utils.ByteUtils;
import com.zemb.flxwear.Utils.DeviceUtils;
import com.zemb.flxwear.Utils.LogUtils;
import com.zemb.flxwear.Utils.VoicePlayUtils;


import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class BloodFourCategoryFragment extends BaseFragment implements View.OnClickListener {

    TextView tvDeviceName, tvStateName, tvTime, tvTemp, tvResult, tvResultState;
    DataBaseHelper.FourCategoryBean fourCategoryBean;
    long measureTime = 0;

    @Override
    int getLoadingPageId() {
        return R.id.loading_page;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_blood_four_category;
    }

    @Override
    void onNotifyCallBack(byte[] data) {
        LogUtils.PrintLog(Arrays.toString(data));
        String[] spl = ByteUtils.bytesToHex(data).split(" ");
        if (spl[0].equals("02") && spl[1].equals("fd")) {
            switch (spl[2]) {
                case "01":
                    //插入试纸
                    // 测量时长为试纸反应时间，为滴血后到输出反应结果的倒计时时间
                    //DATA5： 0X10:仪器正常  0X11:温度过高  0X12:温度过低
                    //判断试纸类型
                    switch (data[4]) {
                        case 0x01:
                            onMeasureStart();
                            tvResultState.setText(getString(R.string.blood_sugar));
                            if (activity.getMeasureTag() != DeviceUtils.Category.BLOOD_SUGAR) {
                                tvResultState.setText(getString(R.string.please_use_blood_sugar_test_paper));
                                VoicePlayUtils.getInstance().playPaperWorse(activity.getMeasureTag());
                            } else {
                                fourCategoryBean.category = DeviceUtils.Category.BLOOD_SUGAR;
                                VoicePlayUtils.getInstance().playPaperRight(activity.getMeasureTag());
                            }
                            break;
                        case 0x02:
                            onMeasureStart();
                            tvResultState.setText(getString(R.string.cholesterol));
                            if (activity.getMeasureTag() != DeviceUtils.Category.CHOLESTEROL) {
                                tvResultState.setText(getString(R.string.please_use_cholesterol_test_paper));
                                VoicePlayUtils.getInstance().playPaperWorse(activity.getMeasureTag());

                            } else {
                                fourCategoryBean.category = DeviceUtils.Category.CHOLESTEROL;
                                VoicePlayUtils.getInstance().playPaperRight(activity.getMeasureTag());
                            }
                            break;
                        case 0x03:
                            onMeasureStart();
                            tvResultState.setText(getString(R.string.uric_acid));
                            if (activity.getMeasureTag() != DeviceUtils.Category.URIC_ACID) {
                                tvResultState.setText(getString(R.string.please_use_uric_acid_test_paper));
                                VoicePlayUtils.getInstance().playPaperWorse(activity.getMeasureTag());
                            } else {
                                fourCategoryBean.category = DeviceUtils.Category.URIC_ACID;
                                VoicePlayUtils.getInstance().playPaperRight(activity.getMeasureTag());
                            }
                            break;
                        case 0x04:
                            onMeasureStart();
                            tvResultState.setText(getString(R.string.blood_ketone));
                            if (activity.getMeasureTag() != DeviceUtils.Category.BLOOD_KETONE) {
                                tvResultState.setText(getString(R.string.please_use_blood_ketone_test_paper));
                                VoicePlayUtils.getInstance().playPaperWorse(activity.getMeasureTag());
                            } else {
                                hideLoading();
                                fourCategoryBean.category = DeviceUtils.Category.BLOOD_KETONE;
                                VoicePlayUtils.getInstance().playPaperRight(activity.getMeasureTag());
                            }
                            break;

                    }

                    //温度
                    tvTemp.setText((double) ByteUtils.bytesToTen(spl[5], spl[6]) / 10 + "");
                    //时长
                    tvTime.setText(Integer.parseInt(spl[7], 16) + "");
                    //仪器状态
                    Log.d("仪器状态", "" + DeviceUtils.deviceState(activity,spl[8]));
                    String state = DeviceUtils.deviceState(activity,spl[8]);
                    tvStateName.setText(state);
                    break;
                case "02":
                    //拔出试纸
                    tvStateName.setText(getString(R.string.please_pull_out_test_paper));
                    break;
                case "03":
                    String toast_text = DeviceUtils.paperState(activity,spl[4]);
                    //试纸状态
                    //0X01:试纸合格、等待滴血    0X02:试纸过期，请拔出试纸
                    //0X10:CODE 卡更新成功    0X11:CODE 卡校验异常    0X12:不支持的 CODE
                    tvStateName.setText(toast_text);
                    break;
                case "04":
                    String surplusTime = Integer.parseInt(spl[4], 16) + "";
                    tvTime.setText(surplusTime);
                    //该测量时间与试纸插入时反馈的测量时长一致，滴血后仪器立即进入倒
                    //计时，倒计时结束后返回测量结果。
                    break;
                case "05":
                    //测量结果
                    String paperType = DeviceUtils.getPaperType(activity,spl[4]);
                    double resultData = 0;
                    if (paperType == "03") {
                        resultData = (double) ByteUtils.bytesToTen(spl[5], spl[6]) / 10;
                    } else {
                        resultData = (double) ByteUtils.bytesToTen(spl[5], spl[6]) / 100;
                    }
                    String statue = DeviceUtils.getStatue(activity,spl[7]);
                    fourCategoryBean.data = resultData;
                    fourCategoryBean.statue = statue;
                    tvResultState.setText(statue);
                    tvResult.setText(resultData + "");
                    // 0X01：正常  0X02:偏高  0X03：偏低
                    onMeasureComplete();
                    break;
                default:
                    break;
            }
        }
    }


    @Override
    protected void initView(View root) {
        tvDeviceName = root.findViewById(R.id.tv_device_name);
        tvStateName = root.findViewById(R.id.tv_state_name);
        tvTime = root.findViewById(R.id.tv_time);
        tvTemp = root.findViewById(R.id.tv_temp);
        tvResult = root.findViewById(R.id.tv_result);
        tvResultState = root.findViewById(R.id.tv_result_state);
        root.findViewById(R.id.v_top_panel).setOnClickListener(this);
        if (activity.getCurrentDevice() != null) {
            tvDeviceName.setText(activity.getCurrentDevice().getName());
        }

    }

    @Override
    protected void initData() {
        fourCategoryBean = new DataBaseHelper.FourCategoryBean();
        if (activity.getMeasureTag() != null) {
            fourCategoryBean.category = activity.getMeasureTag();
        }
    }



    @Override
    public void onMeasureComplete() {
        VoicePlayUtils.getInstance().PlayMeasureSuccess(activity.getMeasureTag());
        showLoading(getResourceString(R.string.measure_complete));
        closeNotify();
        fourCategoryBean.date = System.currentTimeMillis();
        DataBaseHelper.getInstance(activity).addFourCategory(fourCategoryBean);
        if (isAuto) {
            ReportItem item = new ReportItem();
            item.type = fourCategoryBean.category;
            item.result = fourCategoryBean.data + "  " + fourCategoryBean.statue;
            //时间格式 2019/01/01
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            item.time = sdf.format(new Date(fourCategoryBean.date));
            activity.finishTask(item);
            hideLoading();
        }
        hideLoading();
        isMeasure = false;
        isSuccessful = true;
    }


    @Override
    public void onMeasureStart() {
        if (isMeasure||isSuccessful) {
            return;
        }
        VoicePlayUtils.getInstance().PlayMeasureStart(activity.getMeasureTag());
        showLoading(getResourceString(R.string.measuring));
        isMeasure = true;

    }

    @Override
    public String getCharacteristicHead() {
        return "0000fee1";
    }

    @Override
    public void onStartConnectDevice() {
        VoicePlayUtils.getInstance().PlayConnectStart(activity.getMeasureTag());
        showLoading(getResourceString(R.string.connecting));
    }

    private Handler handler;
    @Override
    public void onDeviceConnect(BleDevice bleDevice) {

        VoicePlayUtils.getInstance().PlayConnectSuccess(activity.getMeasureTag());
        hideLoading();
        openNotify();
        tvDeviceName.setText(bleDevice.getName());
        tvStateName.setText(getResourceString(R.string.connect));
        final  int k = 60000;
        //2分钟倒计时如果还未开始检测就完成检测
        //输出倒计时
        new Thread(new Runnable() {
            @Override
            public void run() {
                DeviceUtils.Category category= activity.getMeasureTag();
                for (int i = k/1000; i >= 0; i--) {
                    if(category!=activity.getMeasureTag()){
                        LogUtils.PrintLog("测量类型不一致");
                        LogUtils.PrintLog("current thread = "+ category+"");
                        LogUtils.PrintLog("activity thread = "+ activity.getMeasureTag()+"");
                        return;
                    }
                    LogUtils.PrintLog("倒计时：" + i);
                    try {
                         sleep(1000);

                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
                if(!isMeasure){
                    onMeasureFailed();
                }
            }
        }).start();
    }
    @Override
    public void onDeviceConnectFail(BleDevice bleDevice, BleException exception) {
        hideLoading();
        VoicePlayUtils.getInstance().PlayConnectFailed(activity.getMeasureTag());
    }

    @Override
    public void onDeviceDisConnected(BleDevice bleDevice) {
        if(!isSuccessful&&isMeasure){
            onMeasureFailed();
        }
        VoicePlayUtils.getInstance().PlayDisconnect(activity.getMeasureTag());
        hideLoading();
        isMeasure = false;
        tvDeviceName.setText(getResourceString(R.string.disconnect));
        tvStateName.setText(getResourceString(R.string.disconnect));
//        if(isAuto){
//            ReportItem item =new ReportItem();
//            item.type = fourCategoryBean.category;
//            item.result = "测量失败";
//            //时间格式 2019/01/01
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            item.time = sdf.format(new Date(fourCategoryBean.date));
//            activity.finishTask(item);
//            hideLoading();
//        }
     //   activity.failTask();

    }

    @Override
    void closeNotify() {
        BleManager.getInstance().stopNotify(activity.getCurrentDevice(), service_uuid, characteristic_uuid);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.v_top_panel:
                activity.switchFragment(DeviceUtils.UIType.CONNECT);
                break;
        }
    }


    @Override
    public void restart() {
        super.restart();
        initData();
        switch (activity.getMeasureTag()) {
            case BLOOD_SUGAR:
                tvResultState.setText(getResourceString(R.string.blood_sugar));
                break;
            case BLOOD_KETONE:
                tvResultState.setText(getResourceString(R.string.blood_ketone));
                break;
            case CHOLESTEROL:
                tvResultState.setText(getResourceString(R.string.cholesterol));
                break;
            case URIC_ACID:
                tvResultState.setText(getResourceString(R.string.uric_acid));
                break;
        }

    }
}
